<?php

class AdminController extends Controller {

    public $defaultAction = 'admin';
    private $_model;
    public $layout = '//layouts/adminConsole';

    /**
     * @return array action filters
     */
    public function filters() {
        return CMap::mergeArray(parent::filters(), array(
            'accessControl', // perform access control for CRUD operations
        ));
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        $arrayUser = array_merge(UserModule::getAdmins(),UserModule::getSuppliers());
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index','default','admin', 'delete', 'create', 'update', 'view','active','lock','unlock','upgrade'),
                'users' => $arrayUser,
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $dataProvider = new CActiveDataProvider('User', array(
                    'pagination' => array(
                        'pageSize' => Yii::app()->controller->module->user_page_size,
                    ),
                ));

        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Displays a particular model.
     */
    public function actionView() {
        $model = $this->loadModel();

        $avatar = $this->getAvatarLink($model->avatar);
        $avatarThumbnail = $this->getAvatarThumbnailLink($model->avatar);
        $this->render('view', array(
            'model' => $model,
            'avatar' => $avatar,
            'avatarThumbnail' => $avatarThumbnail,
        ));
    }

    /**
     * Active or inactived a user
     * This page use for ajax
     */
    public function actionActive() {
        $model = $this->loadModel();
        if($model){
            $model->status = User::STATUS_ACTIVE;
            if($model->save()){
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        //$this->render('active');
    }

    /**
     * Lock or un_lock a user
     * This page use for ajax
     */
    public function actionLock() {
        $model = $this->loadModel();
        if($model){
            $model->status = User::STATUS_BANED;
            $model->lock_from = time();
            if($model->save()){
                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        //$this->render('lock');
    }
     /**
     * Lock or un_lock a user
     * This page use for ajax
     */

    /**
     * Upgrade user to other level
     * This page use for ajax
     */
    public function actionUpgrade() {
       // $this->render('upgrade');
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {

        $model = new User;
        //$profile = new Profile;
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            $model->superuser = Yii::app()->getRequest()->getParam('type');
            $model->activkey = Yii::app()->controller->module->encrypting(microtime() . $model->password);
            if (Yii::app()->getModule('user')->isAdmin()||Yii::app()->getModule('user')->isSupplier()) {
                $model->status = User::STATUS_ACTIVE;
            }
            $model->createtime = time();
            $model->lastvisit = time();
            if ($model->validate()) {
                // upload avatar for user
                $model->avatar = CUploadedFile::getInstance($model, 'avatar');
                if ($model->avatar != null) {
                    $avatar_name = 'image_' . $model->id . '_' . time() . '.' . $model->avatar->getExtensionName();
                    $model->avatar->saveAs(Yii::getPathOfAlias('webroot') . User::S_IMAGES . $avatar_name);
                    $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . User::S_IMAGES . $avatar_name);
                    $image->resize(128, 128, Image::HEIGHT);
                    $image->save(Yii::getPathOfAlias('webroot') . User::S_THUMBNAIL . $avatar_name); // or $image->save('images/small.jpg');
                    $model->avatar = $avatar_name;
                } else {
                    $model->avatar = User::S_NOIMAGE;
                }
                $model->password = Yii::app()->controller->module->encrypting($model->password);
                if ($model->save()) {
                    // save distributor of current supplier
                    if (Yii::app()->getModule('user')->isSupplier()) {
                        if (User::S_DISTRIBUTOR == Yii::app()->getRequest()->getParam('type')) {
                            //$dis_sup = new DistributorSupplier;
                            //$dis_sup->dis_id = $model->id;
                            //$dis_sup->sup_id = Yii::app()->user->id;
                            //$dis_sup->save();
                            $model->parent = Yii::app()->user->id;
                            $model->save();
                        }
                    }
                    
                    // save product if is supplier
                    if ($model->superuser == User::S_SUPPLIER){
                        $product = new SupplierProduct();
                        $product->product_id = $_POST['User']['business'];
                        $product->created_time = time();
                        $product->created_by = Yii::app()->user->id;
                        $product->unit = '';
                        $product->unit_price = 0;
                        $product->supplier_id = $model->id;
                        $product->save();
                    }
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }
        $this->render('create', array(
            'model' => $model,
                //'profile'=>$profile,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();
        $avatar = $this->getAvatarLink($model->avatar);
        $avatarThumbnail = $this->getAvatarThumbnailLink($model->avatar);
        $oldAvatar = $model->avatar;
        $model->modified_time = time();
        //$profile=$model->profile;
        if (isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            //$profile->attributes=$_POST['Profile'];

            if ($model->validate()) {
                $old_password = User::model()->notsafe()->findByPk($model->id);
                if ($old_password->password != $model->password) {
                    $model->password = Yii::app()->controller->module->encrypting($model->password);
                    $model->activkey = Yii::app()->controller->module->encrypting(microtime() . $model->password);
                }
                $model->avatar = CUploadedFile::getInstance($model, 'avatar');
                if ($model->avatar != null) {
                    $avatar_name = 'image_' . $model->id . '_' . time() . '.' . $model->avatar->getExtensionName();
                    $model->avatar->saveAs(Yii::getPathOfAlias('webroot') . User::S_IMAGES . $avatar_name);
                    $image = Yii::app()->image->load(Yii::getPathOfAlias('webroot') . User::S_IMAGES . $avatar_name);
                    $image->resize(128, 128, Image::HEIGHT);
                    $image->save(Yii::getPathOfAlias('webroot') . User::S_THUMBNAIL . $avatar_name); // or $image->save('images/small.jpg');
                    $model->avatar = $avatar_name;
                } else {
                    $model->avatar = $oldAvatar;
                }
                $model->save();
                //$profile->save();
                $this->redirect(array('view', 'id' => $model->id));
            } //else $profile->validate();
        }

        $this->render('update', array(
            'model' => $model,
            'avatar' => $avatar,
            'avatarThumbnail' => $avatarThumbnail,
                //'profile'=>$profile,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel();
            //$profile = Profile::model()->findByPk($model->id);
            //$profile->delete();
            $model->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_POST['ajax']))
                $this->redirect(array('/user/admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = User::model()->notsafe()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function saveDistributor() {

    }

    /**
     *  Get Image link
     * @param string $avatar
     * @return string
     */
    static function getAvatarLink($avatar) {
        $avatar_link = Yii::app()->request->baseUrl . User::S_IMAGES . $avatar;
        return $avatar_link;
    }

    /**
     * Get thumbnail of image
     * @param string $avatar
     * @return string or false
     */
    static function getAvatarThumbnailLink($avatar) {
        $avatar_link = Yii::app()->request->baseUrl . User::S_THUMBNAIL . $avatar;
        return $avatar_link;
    }

}